// app/service/user.js
const Service = require('egg').Service;
const Path = require('path');
const uuid = require('uuid');
const fs = require('fs');

function saveStream(stream, filepath) {
  return new Promise((resolve, reject) => {
    const ws = fs.createWriteStream(filepath);
    stream.pipe(ws);
    ws.on('error', reject);
    ws.on('finish', resolve);
  });
}

class MediaService extends Service {
  async upload({
    path,
    size,
    mime,
  }) {
    const row = await this.app.model.transaction(t => this.ctx.model.Media.create({
      path,
      size,
      mime,
    }, {
      transaction: t,
    }));
    return row.dataValues.id;
  }

  async saveMedia(stream) {
    const filePathArray = Path.basename(stream.filename).split('.');
    const extension = filePathArray[filePathArray.length - 1];
    const fileName = `${uuid.v4()}.${extension}`;
    const filePath = `${this.config.uploadDest}/${fileName}`;
    // 文件处理，上传到云存储等等
    await saveStream(stream, filePath);
    return `/web/media/${fileName}`;
  }
}

module.exports = MediaService;
